package com.sgj.interceptors;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.sgj.utils.JWTUtils;
import com.sgj.vo.LoginVo;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 * @Author: Guoji Shen
 * @Date: 2021/12/16 15:14
 */
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的令牌
        String token = request.getHeader("token");
        LoginVo vo = new LoginVo();
        try {
            JWTUtils.verify(token);
            vo.setState(true);
            vo.setMsg("验证成功");
            vo.setToken(token);
            return true;
        } catch (SignatureVerificationException e) {
            vo.setMsg("无效签名");
        } catch (TokenExpiredException e) {
            vo.setMsg("token 过期");
        } catch (AlgorithmMismatchException e) {
            vo.setMsg("算法不一致");
        } catch (Exception e) {
            vo.setMsg("token 无效");
        }
        vo.setState(false);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(JSONObject.toJSONString(vo));
        return false;
    }
}